import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class DataPage extends StatefulWidget {
  const DataPage({Key? key}) : super(key: key);

  @override
  _DataPageState createState() => _DataPageState();
}

class _DataPageState extends State<DataPage> {
  List _list=[];
  //初始化页面时获取商品数据GET1
  @override
  void initState(){
    // TODO: implement initState
    super.initState();
    this._getProduct();
  }

  _getProduct() async{
    //https://jd.itying.com/api/pcate
    var url = Uri.parse('https://api-hmugo-web.itheima.net/api/public/v1/goods/search');
    var response = await http.get(url);
    Map m = json.decode(response.body);
    //非常重要的setState
    setState(() {
      this._list=json.decode(response.body)['message']['goods'];
    });
    // print(m['message']['goods'] is List);
    // print(m['message']['goods']);
    // List listData=m['message']['goods'];
    /* 可以遍历
    for(int i=0;i<listData.length;i++){
      print(listData[i]["goods_name"]);
    }*/
    /* 不好用！
    listData.map((value){
      print("---${value["goods_name"]}");
    });*/
    // print("输出--长度${listData.length}");
    /*this._list=m['message']['goods'];
    print(_list);
    print(this._list[0]['goods_name']);*/
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('数据请求'),
      ),
      body: this._list.length>0?ListView.builder(
              itemCount: _list.length,
              itemBuilder:(context,index){
                return ListTile(
                  leading:Image.network('https://www.itying.com/images/flutter/2.png'),
                  title: Text(this._list[index]['goods_name']),
                  subtitle: Text("${this._list[index]['goods_price']}"),
                );
              }
          ):Text('没数据'),
    );
  }
}
